<template>
    <div>
        <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
        <div class="add">
      <div class="common-layout">
        <el-container>
          <el-main>
            <el-row>
              <el-col :span="24">
                <div class="grid-content ep-bg-purple">
                  <h4>基本信息</h4>
                  <el-form :inline="true" :model="cgsq" :rules="rules" status-icon ref="formRef">
                    <el-form-item label="单据编号" prop="code">
                <el-input
                    v-model="cgsq.code"
                    style="width: 240px"
                    placeholder="请输入单据编号"
                    clearable
                    />
                        </el-form-item>


                    <!-- 客户 -->

                    <!-- 报价日期 -->
                    <el-form-item label="需求日期" prop="get_date">
                      <el-date-picker
                        v-model="cgsq.get_date"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"

                      />
                    </el-form-item>
<!--                    :disabled-date="disabledDate"-->
                    <!-- 报价名称 -->
                    <el-form-item label="备注" prop="info">
                      <el-input
                        v-model="cgsq.info"
                        style="width: 240px"
                        placeholder="备注名称"
                      />
                    </el-form-item>

                    <!-- 业务员 -->
                    <el-form-item label="业务员" prop="uid">
                      <el-select
                          v-model="cgsq.uid"
                          placeholder="请选择业务员"
                          style="width: 240px;"
                          clearable
                      >
                        <el-option
                            v-for="thisUser in userList"
                            :key="thisUser.id"
                            :label="thisUser.name"
                            :value="thisUser.id"
                        />
                      </el-select>
                    </el-form-item>


                    <!-- 部门 -->
                    <el-form-item label="部门" prop="deptId">
                      <el-select
                        v-model="cgsq.deptId"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                        @change="loadUser();cgsq.uid = ''"
                      >
                        <el-option
                          v-for="dept in departments"
                          :key="dept.value"
                          :label="dept.label"
                          :value="dept.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </div>
    </div>
     <div>
      <div class="toolbar">
    <el-button type="primary" @click="check()">商品信息</el-button>
    <el-button @click="addGoodsRow">继续添加</el-button>

  </div>


   <!--TODO 商品详情-->
  <!-- 商品信息表格 -->
  <el-table :data="tableData" border style="width: 100%" class="goods-table">
    <!-- 商品编码（带必填标识的下拉框） -->
    <el-table-column label="商品编码" width="150">
      <template #header>
        <span class="required-label">商品编码</span>
      </template>
      <template #default="scope">
        <el-select
          v-model="scope.row.pcode"
          placeholder="请选择商品"
          @change="handleGoodsChange(scope.row);validatePrice(scope.row)"
          clearable
        >
          <el-option
            v-for="item in goodsOptions"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </template>
    </el-table-column>

    <!-- 商品名称 -->
    <el-table-column label="商品名称" width="180">
      <template #default="scope">{{ scope.row.name || '-' }}</template>
    </el-table-column>

    <el-table-column label="商品型号" width="180">
      <template #default="scope">{{ scope.row.type || '-' }}</template>
    </el-table-column>


    <!-- 单位（带必填标识） -->
    <el-table-column label="单位" width="80" align="center">
      <template #header>
        <span class="required-label">单位</span>
      </template>
      <template #default="scope">{{ scope.row.uname || '件' }}</template>
    </el-table-column>

    <!-- 数量（带必填标识的输入框） -->
    <el-table-column label="数量" width="120" align="center">
      <template #header>
        <span class="required-label">数量</span>
      </template>
      <template #default="scope">
        <el-input-number
          v-model="scope.row.num"
          :min="1"
          :max="scope.row.stock"
          controls-position="right"
          style="width: 100px"
        >
      </el-input-number>
      </template>
    </el-table-column>

    <el-table-column label="建议报价" width="200" align="center">
      <template #default="scope">
        <el-input
          v-model="scope.row.price"
          placeholder="输入报价"
          @focusout="validatePrice(scope.row)"
        >
          <template #append>元</template>
        </el-input>
      </template>
    </el-table-column>

<!--    TODO 价格-->

    <!-- 历史报价（可点击链接） -->
<!--    <el-table-column label="历史报价" width="120" align="center">-->
<!--      <template #default="scope">-->
<!--        <el-link-->
<!--          type="primary"-->
<!--          @click="showHistory(scope.row)"-->
<!--          v-if="scope.row.historyPrice"-->
<!--        >-->
<!--          {{ scope.row.historyPrice }}-->
<!--        </el-link>-->
<!--        <span v-else>-</span>-->
<!--      </template>-->
<!--    </el-table-column>-->

    <!-- 其他只读列 -->
    <el-table-column
      v-for="col in readonlyColumns"
      :key="col.prop"
      :prop="col.prop"
      :label="col.label"
      :width="col.width"
      align="center"
    />
    <el-table-column label="建议供应商" width="150">
      <template #header>
        <span class="required-label">建议供应商</span>
      </template>
      <template #default="scope">
          <el-select
              v-model="scope.row.pro_id"
              placeholder="请选择供应商"
              style="width: 240px;"
              clearable
              filterable
          >
            <el-option
                v-for="pro in proList"
                :key="pro.id"
                :label="pro.name"
                :value="pro.id"
            />
        </el-select>
      </template>
    </el-table-column>

  </el-table>

     </div>
     <div class="total-summary">
      <div class="total-label">合计</div>
      <div class="total-amount">{{ formatTotal }} + {{ totalNum}}</div>
    </div>
     </div>
</template>


<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import {type ComponentSize, ElMessage, type FormInstance, type FormRules} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import type {FunctionalComponent} from 'vue'
import type {Column, InputInstance} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import type { SalesQuotation } from '@/types/public-xs/salesDocuments';
import axios from 'axios';
import type {CGSQ, CGSQInfo} from "@/types/cg/CGSQ.ts";
import type {PubUser} from "@/types/public-cg/User.ts";
import type {CGGood} from "@/types/cg/Util.ts";
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import request from "@/util/request.ts";
import type {CGUser} from "@/types/cw/Public.ts";
let route = useRoute()
let router=useRouter()
let code = route.query.code

  const handleHistory = (row:any) => {
    console.log('查看历史报价:', row)
  }
let proList = ref<PublicProvider[]>([])

const departments = ref([
  { value: 1, label: '生产部门' },
  { value: 2, label: '销售部门'},
  { value: 3, label: '仓管部门'},
  { value: 4, label: '采购部门'},
  { value: 5, label: '财务部门'},
  { value: 10, label: '人事部门'}
])
let userList = ref<CGUser[]>([

])


let cgsq = ref<CGSQ>({
  code: "CG-20250418-0001",
  uid: '',
  info: "",
  status: 0,
  get_date:null,
  total : "",
  type:17
})
let manager = ref<PubUser>({
    name:"testUser",
    dept:"采购部",
})

let addGoodsRow = () => {
  tableData.value.push({
    pid:'0',
    major_code:'',
    num:"0",
    name:""
  })
}


let title=ref('采购申请单') //TODO 订单标题

let checkPassList = [1, 3 , 4 , 11]

 // todo 监听按钮
const handleAction = (action:string) => {
  switch(action) {
    case 'save':
      if (checkPassList.includes(cgsq.value.status)) {
        ElMessage.error("单据无法修改");
        return;
      }
      if (code == null || ''){
        submit();
      }else {
        modi();
      }
      break
    case 'history':
    router.push('cgsq')
      break;
    case 'audit':
      getCGSQ();
      break;
  }
}

// todo  按钮配置
const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'audit',
    label: '审核',
    hidden: true
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }

])

const rules = ref({
  get_date: [{ required: true, message: '请输入需求日期', trigger: 'blur' }],
  deptId:[{required : true , message:'选择部门' ,trigger : 'change'}],
  uid:[{required : true , message:'选择业务员' ,trigger : 'change'}],
})



const goodsOptions = ref<CGGood[]>([])

//采购信息
// const tableData = ref([{
//   goodsCode: 0,
//   quantity: 1,
//   actualPrice: null,
//   historyPrice: '点击查看',
//   vatRate: 13,
//   taxIncludedPrice: 0
// }])

let tableData = ref<CGSQInfo[]>([

])

// 只读列配置
const readonlyColumns = [
  // { prop: 'suggestedPrice', label: '建议价格', width: 120 },
  { prop: 'tax', label: '增值税税率 (%)', width: 150 },
  { prop: 'tax_price', label: '含税单价', width: 120 },
]
//todo  商品详情拓展

// 商品选择处理
// const handleGoodsChange = (row:any) => {
//   const selected = goodsOptions.value.find(item => item.code === row.goodsCode)
//   if (selected) {
//     row.goodsName = selected.name
//     row.unit = selected.uname
//     row.vatRate = selected.tax
//     // row.suggestedPrice = selected.price || 0
//     calculateTaxPrice(row)
//   }
// }

// 商品选择处理
const handleGoodsChange = (row:any) => {
  console.log(row)
  const selected = goodsOptions.value.find(item => item.code === row.pcode)
  console.log(111)
  console.log(selected)
  if (selected) {
    row.name = selected.name
    row.uname = selected.uname
    row.pid = selected.id
    row.tax = selected.tax
    row.type = selected.type
    row.pro_id = selected.pro_id
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
    row.stock = 1
  }
}

// 价格校验
const validatePrice = (row:any) => {
  row.price = Number(row.price)
  if (isNaN(row.price) || row.price < 0){
    row.price = 0
  }
  console.log("price" ,row.price)
  row.price = row.price.toFixed(2)
  calculateTaxPrice(row)
}


// 含税价计算
const calculateTaxPrice = (row:any) => {
  if (row.price && row.tax) {
    row.tax_price = (row.price * (1 + row.tax/100)).toFixed(2)
  }
}


const totalAmount = computed(() => {
  return tableData.value.reduce((sum, row) => {
    const price = Number(row.tax_price) || 0
    const quantity = Number(row.num) || 0
    return sum + (price * quantity)
  }, 0)
})
// TODO 计算金额
// 格式化金额显示
const formatTotal = computed(() => {
  cgsq.value.total = totalAmount.value.toFixed(2)
  return `¥${totalAmount.value.toFixed(2)}`
})
const totalNum = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + Number(row.num || 0);
  }, 0);
});
watch(totalNum, (newTotal) => {
  cgsq.value.total_num = newTotal.toString();
});

async function loadGood(){
  let res = await request.post("basic/good/getAll")
  goodsOptions.value = res.data.data
  console.log(goodsOptions.value)

  let providerRes = await request.post("basic/Provider/selectProviderByPage",{
    "pageNo":1,
    "pageSize" : 10
  })
  proList.value = providerRes.data.data.list
  console.log(proList.value)

}
loadGood();

async function loadUser(){
  let userRes = await request.post("per/user/selectUserByDept",{
    "dept":cgsq.value.deptId
  })
  userList.value = userRes.data.data
}
loadUser()

let formRef = ref<FormInstance>()
async function submit() {
    const formValid = await formRef.value?.validate()
    if (!formValid) return
  let res = await request.post("cg/CGSQ/addCGSQ", cgsq.value)
  //console.log(res.data)
  cgsq.value.code = res.data.data
  console.log("code" , res.data)
  for (let i = 0;i < tableData.value.length ;i++){
    tableData.value[i].major_code = cgsq.value.code
  }
  console.log(tableData)
  let res2 = await request.post("cg/CGSQ/addCGSQInfo", {
    list: tableData.value
  })
  console.log(res2.data)
  if (res.data.code == 200 && res2.data.code==200){
    router.push('cgsq')
  }
}


//查询商品集合  TODO
async function getCGSQ(){
  console.log(code)
  let res = await request.post("cg/CGSQ/getCGSQ", null , {params:{code}})

  console.log(res.data)
  cgsq.value = res.data.data

  let res2 = await request.post("cg/CGSQ/getCGSQInfo", null, { params: { code } });
  console.log(res2.data.data)
  tableData.value = res2.data.data
}

if (code == null || ''){
    // todo 可获取编码
}else {
  getCGSQ()
}


async function modi(){
  const formValid = await formRef.value?.validate()
  if (!formValid) return
  let res = await request.post("cg/cgCGSQ/modiCGSQ", cgsq.value)
  let res2 = await request.post("cg/cgCGSQ/modiCGSQInfo", {
    list: tableData.value,
    code:code
  })
  // alert(res.data.code +"+ " + res2.data.code)
  if (res.data.code == 200 && res2.data.code==200){
    router.push('cgsq')
  }
}
function check(){
  console.log(tableData.value)
  console.log(cgsq.value)
}
</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}

</style>